<?php

namespace app\admin\model;

use think\facade\Db;

class Pay
{
    private $table = 'config';

    /**
     * 获取.
     */
    public function get($type)
    {
        $info = Db::name($this->table)
            ->where('type', $type)
            ->column('value', 'field');

        return success('操作成功', $info);
    }

    /**
     * 设置.
     */
    public function set($params)
    {
        $list = Db::name($this->table)
            ->where('type', $params['type'])
            ->column('id', 'field');

        $fields = [
            'app_id', 'app_secret', 'mch_id', 'mch_key', 'cert_path', 'key_path',
            'ali_app_id', 'ali_public_key', 'ali_private_key',
        ];
        foreach ($fields as $field) {
            if (empty($params[$field])) {
                continue;
            }
            $data[$field] = $params[$field];
        }

        Db::startTrans();
        try {
            $insert = [];
            foreach ($data as $field => $value) {
                if (empty($list[$field])) {
                    $insert[] = [
                        'type' => $params['type'],
                        'name' => '',
                        'field' => $field,
                        'value' => $value,
                    ];
                } else {
                    Db::name($this->table)
                        ->where('id', $list[$field])
                        ->update([
                            'value' => $value,
                        ]);
                }
            }
            if ($insert) {
                Db::name($this->table)->insertAll($insert);
            }

            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();

            return fail('操作失败：'.$e->getMessage());
        }

        return success('操作成功');
    }

    /**
     * 上传证书.
     */
    public function uploadCert()
    {
        try {
            $file = request()->file('file');
            // 上传到本地服务器
            $savePath = date('Ymd').'/'.md5((string) microtime(true)).'/'.$file->getOriginalName();
            $savename = \think\facade\Filesystem::disk('cert')->putFileAs('cert', $file, $savePath);
            $savename = str_replace('\\', '/', $savename);
        } catch (\Exception $e) {
            return fail('上传失败：'.$e->getMessage());
        }

        return success('上传成功', [
            'url' => $savename,
        ]);
    }
}
